const Router = require('koa-router')
const router = new Router()
const crypto = require('crypto');
const log = require('../utils/log')

function hashPW(userName, pwd) {
    var hash = crypto.createHash('md5');
    hash.update(userName + pwd);
    return hash.digest('hex');
}

const allowList = ['/login', '/favicon.ico', '/logout']

//exports 的 router ，所以，对外使用的 fun，放在 royter 下
//单独 exports localFilter 的话， router 的饮用方式也要改变
router.localFilter = (ctx) => {
    //if (ctx.path === '/favicon.ico') return

    let url = ctx.originalUrl
    if (allowList.indexOf(url) > -1) {
        console.log('当前地址可直接访问==', url)
    } else {
        if (getCookie(ctx)) {
            console.log('登录验证成功！')
            //这里会直接访问 originalUrl
        } else {
            console.log('当前地址需要登录验证！', url)
            message.prevUrl = url
            ctx.redirect('/login')
        }
    }
}

//这里直接写死了，实际可以配置 config 设置
const setCookie = (ctx, userName, hash, lastTime) => {
    console.log("setCookie===")
    ctx.cookies.set(message.sessionKey,
        userName,
        //{ account: userName, hash: hash, last: lastTime },
        { maxAge: 24 * 60 * 60000 })
}

const getCookie = (ctx) => {
    try {
        let cookie = ctx.cookies.get(message.sessionKey)
        console.log("cookie=", cookie)
        if (typeof (cookie) == 'undefined')
            return null
        else
            return cookie
    } catch (err) {
        console.log(err)
        return null
    }
}

const clearCookie = ctx => {
    ctx.cookies.set(message.sessionKey, null, { maxAge: 0 })
    console.log('getCookie(ctx) after clear ==', getCookie(ctx))
}

var userdb = [
    {
        userName: "wzh2018",
        hash: hashPW("wzh2018", "wzh@88553212"),
        hash2: hashPW("wzh2018", "wzh@88553216"),
        last: ""
    },
    {
        userName: "mlj2018",
        hash: hashPW("mlj2018", "mlj@88553212"),
        hash2: hashPW("mlj2018", "mlj@88553216"),
        last: ""
    }
];

function getLastLoginTime(userName) {
    for (var i = 0; i < userdb.length; ++i) {
        var user = userdb[i];
        if (userName === user.userName) {
            return user.last;
        }
    }
    return "";
}

function updateLastLoginTime(userName) {
    for (var i = 0; i < userdb.length; ++i) {
        var user = userdb[i];
        if (userName === user.userName) {
            user.last = Date().toString();
            return;
        }
    }
}

function authenticate(userName, hash) {
    for (var i = 0; i < userdb.length; ++i) {
        var user = userdb[i];
        if (userName === user.userName) {
            if (hash === user.hash) {
                return 0;
            } else {
                return 1;
            }
        }
    }
    return 2;
}

function hasLogined(ctx) {
    return getCookie(ctx)
};

let errMsg = null
let message = require("../utils/config").message
router.get('/login', async (ctx, next) => {
    //如果已经登录过，就直接返回首页，或者跳转过来的原始页

    if (message.prevUrl != null) {
        if (getCookie(ctx) != null) {
            console.log('getCookie(ctx) 333 on login ==', getCookie(ctx))
            message.hasLogined = getCookie(ctx).account
            //ctx.redirect('/index')
            //这里应该是哪里来的，回去哪里
            ctx.redirect(message.prevUrl)
        }
    }

    await ctx.render('login', {
        title: 'login 登录',
        csrf: ctx.csrf,
        errMsg: errMsg
    }
    )
}
)

router.post('/login', async (ctx, next) => {
    //console.log(ctx.request.body)
    var userName = ctx.request.body.login_username
    var hash = hashPW(userName, ctx.request.body.login_password)
    //记录日志
    log.info('login: >', userName)

    switch (authenticate(userName, hash)) {
        case 0: //success
            var lastTime = getLastLoginTime(userName)
            updateLastLoginTime(userName)
            console.log("login ok, lastTime - " + lastTime)
            setCookie(ctx, userName, hash, lastTime)
            //显示登录名称
            message.hasLogined = userName
            //这里应该是哪里来的，回去哪里
            if (message.prevUrl == null)
                ctx.redirect('/index')
            else
                ctx.redirect(message.prevUrl)

            break;
        case 1: //password error
            console.log("password error")
            //ctx.body = { msg: "密码错误" }
            errMsg = "密码错误"
            ctx.redirect('/login')
            break;
        case 2: //user not found
            console.log("user not found");
            errMsg = "用户名不存在"
            ctx.redirect('/login')
            break;
    }

    await next()
}
)

router.get('/logout', async (ctx, next) => {
    //记录日志
    log.info('logout: >', message.hasLogined)

    clearCookie(ctx)
    console.log('logout=====')
    ctx.redirect("/login")
    await next()
})

module.exports = router

